package cn.xdf.controller;

import cn.xdf.entity.Province;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/demo02")
public class Demo02Controller {
    /**
     * 获取请求体的参数
     *
     * @param str
     * @param response
     * @throws Exception
     */
    @RequestMapping("/demo01")
    public void demo01(@RequestBody String str, HttpServletResponse response) throws Exception {
        // 获取请求体的内容

        System.out.println(str);
        response.getWriter().write(str);
        System.out.println("--------------");
    }

    /**
     * 把JSON数据（application/json）转换为Java对象,要求前端传json过来 就是参数加了@RequestBody
     *
     *
     * ，结果是表单，报错415参数不对
     *表单的数据格式 content-type=application/x-www-form-urlencoded  text/htmlcheset是html数据类型
     * 提交就要是表单的数据格式 body:username=admin&age=10 json对象 {id:20,name:"zhangsan"}
     * json的数据格式 application/json
     *json字符串{'id':'10','name':'zhangsan'}
     * @param province
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/demo02")
    public Province demo02(@RequestBody Province province) throws Exception {
        System.out.println(province);
        return province;
    }

    /**
     * 接收表单提交的数据(JSON对象也可以)就是参数不加@RequestBody
     * @param province
     * @return
     * @throws Exception
     */
    @RequestMapping("/demo03")
    @ResponseBody
    public Province demo03(Province province)throws Exception{
        return province;
    }


    /**
     * 使用HttpEntity当做参数
     *
     * @param entity
     * @throws Exception
     */
    @RequestMapping("/demo04")
    @ResponseBody
    public String demo04(HttpEntity<String> entity)throws Exception{
        //获取请求头
        HttpHeaders headers=entity.getHeaders();
        System.out.println(headers);

        //获取请求体
        String provinceJsonStr= entity.getBody();
        System.out.println(provinceJsonStr);

        return provinceJsonStr;
    }

    /**
     * 使用HttpEntity当做参数(封装成对象)
     * 必须要求前端提交的类型为application/json
     *
     * @param entity
     * @throws Exception
     */
    @RequestMapping("/demo05")
    @ResponseBody
    public Province demo05(RequestEntity<Province> entity) throws Exception {

        // 获取请求头
        HttpHeaders headers = entity.getHeaders();
        System.out.println(headers);

        // 获取请求体
        Province province = entity.getBody();
        System.out.println(province);

        return province;
    }



}
